# VideoFeed.py
import io
from threading import Condition
from flask import Flask, Response
from picamera2 import Picamera2
from picamera2.encoders import JpegEncoder
from picamera2.outputs import FileOutput
import time

app = Flask(__name__)

# 自定义流式输出类
class StreamingOutput(io.BufferedIOBase):
    def __init__(self):
        super().__init__()
        self.frame = None
        self.condition = Condition()

    def write(self, buf):
        with self.condition:
            self.frame = buf
            self.condition.notify_all()
        return len(buf)

# 初始化相机
picam2 = Picamera2()
video_config = picam2.create_video_configuration(
    main={"size": (640, 480), "format": "RGB888"},
    controls={"FrameDurationLimits": (66666, 66666)}  # 15 FPS
)
picam2.configure(video_config)

# 设置 JPEG 编码器和输出
output = StreamingOutput()
encoder = JpegEncoder()
picam2.start_recording(encoder, FileOutput(output))

# 生成 MJPEG 流
def generate():
    while True:
        with output.condition:
            output.condition.wait()
            frame = output.frame
        yield (
            b'--frame\r\n'
            b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n'
        )
        time.sleep(0.001)

@app.route('/video_feed')
def video_feed():
    return Response(generate(), mimetype='multipart/x-mixed-replace; boundary=frame')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
